package controller

import (
	"html"
	"log"
	"net/http"
	"strings"
	"traffic/system"
	"traffic/utils"
)

//输出规则
func OutRule() {

}

func CreateVisitMap(r *http.Request, tokens map[string]interface{}) map[string]string {
	visitMap := make(map[string]string)
	visitMap["ip"] = getRealIp(r)
	visitMap["referer"] = r.Referer()
	for k, _ := range tokens {
		visitMap[k] = r.FormValue(k)
	}

	return visitMap
}

//替换输出的变量
func ReplaceCont(mp map[string]interface{}, s string) string {
	s = html.UnescapeString(s)
	log.Println("mp:", mp)
	for k, v := range mp {
		if strings.Contains(s, k) {
			s = strings.Replace(s, "$"+k+"$", v.(string), -1)
		}
	}
	return s
}

func GetTokenRule(ruleid string) ([]map[string]interface{}, error) {
	sql := "select * from ads_ruletoken where `ruleid` ='" + ruleid + "'"
	rows, err := system.Db.Query(sql)
	utils.Chkerr(err)
	if err != nil {
		return nil, err
	}
	ad_data := utils.SqlResolve(rows)
	return ad_data, nil
}

func TokenLogic(r *http.Request, vo map[string]interface{}) bool {
	rule_res := true
	rule_id, _ := vo["id"].(string)
	if vo["tokenlogic"] == "on" {
		tokenrules, _ := GetTokenRule(rule_id)
		log.Println("www:", tokenrules, len(tokenrules))

		if len(tokenrules) == 0 {
			return true
		}

		for _, trule := range tokenrules {
			log.Println("trule", trule)
			log.Println("TokenLogic: ", trule["token"], " ", trule["logic"], " ", trule["val"], "     url", r.FormValue(trule["token"].(string)))
			if trule["logic"] == "veq" {
				if r.FormValue(trule["token"].(string)) != trule["val"] {
					log.Println(trule["token"], "!=", trule["val"])
					rule_res = false
				}
			}
			if trule["logic"] == "vneq" {
				if r.FormValue(trule["token"].(string)) == trule["val"] {
					rule_res = false
				}
			}

			if trule["logic"] == "vin" || trule["logic"] == "vnotin" {
				var inres bool
				truleVals := strings.Split(trule["val"].(string), ",")

				if trule["logic"] == "vin" {
					inres = false
					for _, v := range truleVals {
						if r.FormValue(trule["token"].(string)) == v {
							inres = true
							break
						}
					}
				}

				if trule["logic"] == "vnotin" {
					inres = true
					for _, v := range truleVals {
						if r.FormValue(trule["token"].(string)) == v {
							inres = false
						}
					}
				}

				rule_res = inres
			}
			log.Println(rule_res)

			if rule_res == false {
				break
			}
		}

		if rule_res == false {
			log.Println("规则:", vo["rulename"], "TokenLogic 跳过")
		}

	}
	return rule_res
}
